package cn.tpshion.task.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ObjectUtils;

public class MsgHandlerFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private final List<MsgHandler> handlerList = new ArrayList<>();


    @Override
    public void afterPropertiesSet() {
        Map<String, MsgHandler> beans = applicationContext.getBeansOfType(MsgHandler.class);
        if (ObjectUtils.isEmpty(beans)) {
            return;
        }

        handlerList.addAll(beans.values());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public MsgHandler getHandler(Integer action) {
        for (MsgHandler handler : handlerList) {
            if (handler.support(action)) {
                return handler;
            }
        }
        return null;
    }
}
